package com.party.system.utils;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;

/**
 * @FileName: kcsm
 * @author: 王晨旭
 * @date: 2025/3/12 15:19
 * @Description:
 */
public class WxQRCodeGeneration {

    private   static   String       xcx_appId="wx12c58d065bbcf89e";
    private   static   String       xcx_secretKey="92b7c1125532ab85893730b48663a218";

    public static String getAccessToken() throws IOException {
        String tokenUrl = String.format(
                "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s",
                xcx_appId, xcx_secretKey
        );

        String response = HttpUtil.get(tokenUrl);
        JSONObject jsonResponse = JSON.parseObject(response);

        if (jsonResponse.containsKey("errcode")) {
            System.err.println("微信 API 错误: " + jsonResponse);
            return null;
        }

        return jsonResponse.getString("access_token");
    }

    // **不需要 scene，使用 getwxacode**
    public static byte[] generateWxCode(String accessToken, String page, String outputPath) throws IOException {
        String url = "https://api.weixin.qq.com/wxa/getwxacode?access_token=" + accessToken;

        JSONObject params = new JSONObject();
        params.put("path", page);
        params.put("width", 150);
        params.put("is_hyaline", true);
        params.put("env_version", "develop");


        byte[] imageBytes = sendPostRequest(url, params.toString());

        // **检查是否返回 JSON（错误信息）**
        String responseString = new String(imageBytes, StandardCharsets.UTF_8);
        if (responseString.startsWith("{")) {
            System.err.println("微信 API 错误: " + responseString);
        }

        Files.write(Paths.get(outputPath), imageBytes);
        return imageBytes;
//        System.out.println("小程序码已生成：" + outputPath);
    }

    public static byte[] sendPostRequest(String url, String json) throws IOException {
        HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
        conn.setRequestMethod("POST");
        conn.setDoOutput(true);
        conn.setRequestProperty("Content-Type", "application/json");

        try (OutputStream os = conn.getOutputStream()) {
            os.write(json.getBytes(StandardCharsets.UTF_8));
        }

        try (InputStream is = conn.getInputStream()) {
            return readAllBytes(is);
        }
    }

    public static byte[] readAllBytes(InputStream inputStream) throws IOException {
        ByteArrayOutputStream buffer = new ByteArrayOutputStream();
        byte[] data = new byte[4096];
        int bytesRead;
        while ((bytesRead = inputStream.read(data, 0, data.length)) != -1) {
            buffer.write(data, 0, bytesRead);
        }
        return buffer.toByteArray();
    }

    public static void main(String[] args) throws IOException {


//        String accessToken = getAccessToken(appId, appSecret);


        System.out.println("小程序码已生成，保存为 qrcode.png");
    }
}
